<template>
  <div class="layout-container" style="padding: 0px;margin:0px;width:100vw;max-width:100vw; height:100%">

    <el-row>

      <el-col :span="3">

        <el-affix :offset="80">
          <el-button type="primary" link @click="$router.back()">
            <svg t="1713500080160" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="5133" width="32" height="32">
              <path
                d="M512 1024a512 512 0 1 1 512-512 512 512 0 0 1-512 512z m0-992a480 480 0 1 0 480 480A480 480 0 0 0 512 32z m16 527.616v63.824a32 32 0 0 1-49.744 26.544l-192-127.632a31.856 31.856 0 0 1 0-53.104l192-127.632A32 32 0 0 1 528 368.16V432a191.728 191.728 0 0 1 192 191.44 114.624 114.624 0 0 1-16 64.368c-30.896-73.92-93.264-128.112-176-128.192zM496 464v-90.496a45.552 45.552 0 0 0-22.576 4.592L323.2 477.024a22.752 22.752 0 0 0-11.696 19.728A26.08 26.08 0 0 0 323.2 518.4l150.224 92.432a51.328 51.328 0 0 0 22.576 5.6V528c183.472 0 208.32 122.784 208.32 122.784C704.32 505.6 592 464 496 464z"
                fill="#1296db" p-id="5134"></path>
            </svg>
          </el-button>
          <!-- <h6> 双击文件保存到本地</h6> -->
        </el-affix>

        <el-affix :offset="120">
          <div style="min-width: 180px;">

            <el-descriptions :title="task_name" style="margin-left: 20px;margin-top: 10px;" />
            <el-descriptions title="学生列表" style="margin-left: 20px;margin-top: 10px;" />

            <el-menu style="overflow-x: hidden; min-height: 200px; height: 600px;" @select="handleSelect"
              :default-active="String(defaultStudentIndex)" @open="handleOpen" @close="handleClose">

              <el-menu-item v-for="(item, index) in studentList" :index="String(index)" :key="item.user_id">
                <span>{{ item.user_id }} {{ item.name }}</span>
              </el-menu-item>
            </el-menu>
          </div>

        </el-affix>

      </el-col>
      <el-col :span="4">

        <el-affix :offset="120">
          <div class="layout-container"
            style="margin: 10px;height: 45vh;width:180px;min-width: 180px; overflow-y: auto;overflow-x: hidden;">
            <el-tooltip content="单击在线查看，双击保存到本地" placement="top">
              <el-descriptions :column="1" title="学生提交的文件">

                <el-descriptions-item style="font-size: 16px; color: #666;" v-for="(file, index) in existingFiles"
                  :key="index">
                  <el-link type="primary" :underline="false" @dblclick.stop="downloadFile(file)"
                    @click.stop="showFile(file)">
                    {{ index + 1 }}、{{ file }}
                  </el-link>

                </el-descriptions-item>
                <el-descriptions-item v-if="existingFiles.length === 0">
                  暂无文件
                </el-descriptions-item>

              </el-descriptions>
            </el-tooltip>
            <el-descriptions :column="1" v-if="zipList.length !== 0" :title="selectedFileName">
              <el-descriptions-item style="font-size: 16px; color: #666;" v-for="(file, index) in zipList" :key="index">
                <el-link type="primary" :underline="false" @dblclick.stop="downloadZipFile(file)"
                  @click.stop="showZipFile(file)">
                  {{ index + 1 }}、{{ file.fileName }}
                </el-link>
              </el-descriptions-item>
            </el-descriptions>

          </div>
          <div class="layout-container" style="margin: 10px;width:180px;min-width: 180px;height:auto">

            <el-descriptions :column="1" title="打分">

              <el-descriptions-item label='自动跳转下一个学生'>
                <el-switch v-model="autoNext" />
              </el-descriptions-item>

              <el-descriptions-item>
                <el-input-number @keydown.enter="submitScore" v-model="score" :min="0" :max="max_score" />
              </el-descriptions-item>
              <el-descriptions-item>
                任务总分：{{ max_score }}
              </el-descriptions-item>

              <el-descriptions-item>
                <el-button type="primary" @click="submitScore">提交</el-button>
              </el-descriptions-item>

              <el-descriptions-item>
                <el-button type="primary" style="width:50px" @click="goPrevStudent">上一个</el-button>
                <el-button type="primary" style="width:50px" @click="goNextStudent">下一个</el-button>
              </el-descriptions-item>

            </el-descriptions>
            <!-- </div>
          <div style="margin: 10px;"> -->

            <el-descriptions :column="1" title="分数">
              <el-descriptions-item v-if="selectedItem">
                {{ selectedItem.score }}
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions :column="1" title="状态">
              <el-descriptions-item v-if="selectedItem">
                <span v-if="selectedItem.status === '已发布'">{{ selectedItem.status }}</span>
                <span v-else>{{ selectedItem.status }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-affix>
      </el-col>
      <el-col :span="17">
        <div style="margin: 10px;text-align: left;">
          <VueOfficeDocx v-if="selectedFileType === 'docx' || selectedFileType === 'doc'" :src="selectedFile" />

          <iframe v-if="selectedFileType === 'pdf'" style="width: 1200px; height: 1400px;" :src="selectedFile" />
          <!-- <VueOfficePdf v-if="selectedFileType === 'pdf'" :src="selectedFile" /> -->
          <VueOfficeExcel v-if="selectedFileType === 'xlsx' || selectedFileType === 'xls'" :src="selectedFile"
            style="height: 1000px;" />

          <RenderJupyterNotebook v-if="selectedFileType === 'ipynb' && selectedFile" :notebook="selectedFile" />

          <img
            v-if="selectedFileType === 'png' || selectedFileType === 'jpg' || selectedFileType === 'jpeg' || selectedFileType === 'gif'"
            :src="selectedFile" width="auto" height="auto" />
          <!-- 判断文件后缀是否是图片，如果是图片，则显示图片，否则显示iframe -->
        </div>
      </el-col>

    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, onActivated } from 'vue'

import { getStudentTaskListApi, setTaskScoreApi } from '@/api/course'
import { useStore } from 'vuex'
import { getSelectedStudentFileApi } from '@/api/file';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeExcel from '@vue-office/excel'
import JSZip from "jszip";
import RenderJupyterNotebook from "render-jupyter-notebook-vue"
const router = useRouter()
onActivated(() => {
  console.log('onActivated')
})
onMounted(() => {
  // console.log('mounted')

  console.log('onMounted')
  console.log('history.state = ', history.state)
  setTimeout(() => {
    getStudentTaskListApi({
      task_id: history.state.task_id,
      course_id: history.state.course_id,
    }).then((res: any) => {
      if (res.code === 200) {
        studentList.value = res.data
        existingFiles.value = studentList.value[history.state.index]['file_list']
        selectedItem.value = studentList.value[history.state.index];
        if (existingFiles.value.length > 0) {
          console.log('existingFiles.value[0] = ', existingFiles.value[0])
          showFile(existingFiles.value[0])
        }
      } else {
        ElMessage.error(res.message)
      }
    })
    // existingFiles.value = studentList.value[history.state.index]['file_list']
    max_score.value = history.state.max_score
    defaultStudentIndex.value = history.state.index
    task_name.value = history.state.task_name

  }, 200)
  console.log('studentList = ', studentList.value)
  console.log('selectedItem = ', selectedItem)
  console.log('history.state.index = ', history.state.index)
  console.log('defaultStudentIndex.value = ', defaultStudentIndex.value)
  console.log('max_score.value = ', max_score.value)
})

onBeforeUnmount(() => {
});

const store = useStore()
const task_name = ref(null)
const score = ref(null)
const autoNext = ref(true)
const studentList = ref(null)

const selectedFile = ref(null)
const selectedFileName = ref(null)
const selectedItem = ref(null);
const defaultStudentIndex = ref(null)
const max_score = ref(100)
const resetPage = (index: number) => {
  defaultStudentIndex.value = index
  selectedItem.value = studentList.value[index]
  existingFiles.value = studentList.value[index]['file_list']
  score.value = 0
  zipList.value = []
  selectedFile.value = null
  selectedFileName.value = null
  if (existingFiles.value.length > 0) {
    showFile(existingFiles.value[0])
  }
}
const handleSelect = (index: string) => {
  if (selectedItem.value == studentList.value[parseInt(index)])
    return
  resetPage(parseInt(index))

};
const goNextStudent = () => {
  const index = defaultStudentIndex.value + 1
  if (index < studentList.value.length)
    resetPage(index)
}

const goPrevStudent = () => {
  const index = defaultStudentIndex.value - 1
  if (index >= 0)
    resetPage(index)
}
const selectedFileType = ref(null)
const existingFiles = ref([])
//将base64转换为blob
const dataURLtoBlob = (dataurl: string) => {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) { u8arr[n] = bstr.charCodeAt(n); }
  return new Blob([u8arr], { type: mime });
}

const showZipFile = (file: any) => {
  console.log('file = ', file)
  const content = file.content
  const type = file.type
  selectedFile.value = content
  selectedFileType.value = type
  console.log('showZipFile = ', file)
}

const zipList = ref([])
const showFile = (file: string) => {
  if (selectedFileName.value === file) return
  console.log('file = ', file)
  console.log('selectedItem.value = ', selectedItem.value)
  selectedFileName.value = file
  selectedFileType.value = file.split('.').pop()
  const params = ref({
    file_name: file,
    task_id: history.state.task_id,
    user_id: selectedItem.value.user_id,
  })
  console.log('selectedFileType.value = ', selectedFileType.value)

  getSelectedStudentFileApi(params.value).then((res: any) => {
    console.log('res = ', res)
    if (res.code === 200) {
      if (selectedFileType.value === 'zip') {
        console.log("查看压缩包文件：", res.data.file_content)
        const blob = dataURLtoBlob(res.data.file_content)
        JSZip.loadAsync(blob).then((zip: any) => {
          zipList.value = []
          for (const key in zip.files) {
            if (!zip.files[key].dir) { // 判断是否是目录
              // 判断是否是图片格式
              if (/\.(png|jpg|jpeg|gif)$/.test(zip.files[key].name)) {
                const base = zip.file(zip.files[key].name).async(
                  'base64') // 将图片转化为base64格式
                base.then((res: any) => {
                  // 解压后的文件放到dataList数组，可直接在image标签中展示
                  zipList.value.push({
                    fileName: zip.files[key].name,
                    type: 'img',
                    content: `data:image/png;base64,${res}`
                  })
                })
              }
              // 判断是否是文本文件
              else if (/\.(txt)$/.test(zip.files[key].name)) {
                const base = zip.file(zip.files[key].name).async(
                  'string') // 以字符串形式输出文本内容
                base.then((res: any) => {
                  // 解压后的文件放到dataList数组
                  zipList.value.push({
                    fileName: zip.files[key].name,
                    type: 'text',
                    content: res
                  })
                })
              }
              else {
                const filetype = ref(zip.files[key].name.split('.').pop())
                const base = zip.file(zip.files[key].name).async(
                  'base64') // 以字符串形式输出文本内容
                const prefix = ref('')
                if (filetype.value === 'docx') {
                  prefix.value = 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,'
                }
                else if (filetype.value === 'doc') {
                  prefix.value = 'data:application/msword;base64,'
                }
                else if (filetype.value === 'pdf') {
                  prefix.value = 'data:application/pdf;base64,'
                }
                else if (filetype.value === 'xlsx') {
                  prefix.value = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
                }
                else if (filetype.value === 'xls') {
                  prefix.value = 'data:application/vnd.ms-excel;base64,'
                } else {
                  // ipynb文件, md文件等
                  prefix.value = 'data:application/octet-stream;base64,'
                }

                base.then((res: any) => {
                  // 解压后的文件放到dataList数组
                  zipList.value.push({
                    fileName: zip.files[key].name,
                    type: filetype.value,
                    content: prefix.value + res
                  })
                })
              }
            }
          }
          console.log('zipList.value = ', zipList.value)
        })
        selectedFile.value = null
      } else if (selectedFileType.value === 'ipynb') {
        selectedFile.value = null
        setTimeout(() => {
          selectedFile.value = res.data.file_content
        }, 200)
      } else {
        selectedFile.value = res.data.file_content
        if (selectedFileType.value === 'pdf') {
          showDetailedPosScore(res.data.pos)
        }
      }
    }
  })
}
const showDetailedScore = ref(false)
const showDetailedPosScore = (pos: any) => {
  showDetailedScore.value = true

}
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const submitScore = () => {
  console.log(score.value)
  const params = ref({
    task_id: history.state.task_id,
    stu_id: selectedItem.value.user_id,
    score: score.value,
    user_id: store.state.user.user_id,
  })
  setTaskScoreApi(params.value).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('打分成功，待发布')
      selectedItem.value.score = score.value
      selectedItem.value.status = '已批改'
      if (autoNext.value) {
        const index = defaultStudentIndex.value + 1
        if (index < studentList.value.length) {
          defaultStudentIndex.value = index
          selectedItem.value = studentList.value[index]
          existingFiles.value = studentList.value[index]['file_list']
          score.value = 0
        }

      }
    }
  })
}
const downloadFile = (fileName: string) => {
  const params = ref({
    file_name: fileName,
    task_id: history.state.task_id,
    user_id: selectedItem.value.user_id,
  })
  ElMessage.success('准备下载')
  getSelectedStudentFileApi(params.value).then((res: any) => {
    const blob = dataURLtoBlob(res.data.file_content)
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  })
}
const downloadZipFile = (file: any) => {
  for (const key in zipList.value) {
    if (zipList.value[key].fileName === file.fileName) {
      const blob = dataURLtoBlob(zipList.value[key].content)
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = file.fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      break
    }
  }
}
const getTaskList = () => {
  const params = ref({
    course_id: history.state.course_id,
    task_id: history.state.task_id,
  })
  getStudentTaskListApi(params.value).then((res: any) => {
    if (res.code === 200) {
      studentList.value = res.data
      console.log('studentList.value = ', studentList.value)
    }
  })

}
// getTaskList()
</script>